{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "import gym\n",
    "import pygame\n",
    "from nes_py.wrappers import JoypadSpace\n",
    "from gym_super_mario_bros.actions import COMPLEX_MOVEMENT\n",
    "\n",
    "# 初始化游戏环境\n",
    "env = gym.make(\"SuperMarioBros-1-1-v0\", apply_api_compatibility=True, render_mode=\"human\")\n",
    "env = JoypadSpace(env, COMPLEX_MOVEMENT)\n",
    "\n",
    "# 初始化 Pygame\n",
    "pygame.init()\n",
    "screen = pygame.display.set_mode((400, 300))\n",
    "pygame.display.set_caption(\"Super Mario Manual Play\")\n",
    "\n",
    "# 按键映射（支持组合动作）\n",
    "key_mapping = {\n",
    "    pygame.K_RIGHT: 'right',\n",
    "    pygame.K_LEFT: 'left',\n",
    "    pygame.K_a: 'A',  # 跳跃\n",
    "    pygame.K_b: 'B',  # 冲刺\n",
    "    pygame.K_UP: 'up',\n",
    "    pygame.K_DOWN: 'down'\n",
    "}\n",
    "\n",
    "# 记录当前按下的按键\n",
    "pressed_keys = set()\n",
    "\n",
    "state, _ = env.reset()\n",
    "done = False\n",
    "\n",
    "while not done:\n",
    "    env.render()\n",
    "    action = []  # 当前帧的动作列表\n",
    "\n",
    "    # 监听事件\n",
    "    for event in pygame.event.get():\n",
    "        if event.type == pygame.QUIT:\n",
    "            done = True\n",
    "        elif event.type == pygame.KEYDOWN:\n",
    "            if event.key in key_mapping:\n",
    "                pressed_keys.add(key_mapping[event.key])  # 记录按下的键\n",
    "        elif event.type == pygame.KEYUP:\n",
    "            if event.key in key_mapping:\n",
    "                pressed_keys.discard(key_mapping[event.key])  # 释放按键\n",
    "\n",
    "    # 组合动作（例如 [\"right\", \"A\"] 表示跳跃+前进）\n",
    "    action = list(pressed_keys)\n",
    "\n",
    "    # 找到 `COMPLEX_MOVEMENT` 里对应的索引\n",
    "    if action in COMPLEX_MOVEMENT:\n",
    "        action_index = COMPLEX_MOVEMENT.index(action)\n",
    "    else:\n",
    "        action_index = 0  # 默认不动\n",
    "\n",
    "    # 执行动作\n",
    "    state, reward, done, truncated, info = env.step(action_index)\n",
    "\n",
    "pygame.quit()\n",
    "env.close()\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
